package pers.sen.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.sen.health.aliyunoss.AliyunUtils;
import pers.sen.health.dto.SetmealDTO;
import pers.sen.health.entity.PageResult;
import pers.sen.health.entity.QueryPageBean;
import pers.sen.health.entity.Result;
import pers.sen.health.general.EmptyUtil;
import pers.sen.health.mapper.CheckGroupMapper;
import pers.sen.health.mapper.SetMealMapper;
import pers.sen.health.po.CheckGroup;
import pers.sen.health.po.CheckItem;
import pers.sen.health.po.Setmeal;
import pers.sen.health.redis.RedisUtil;
import pers.sen.health.resources.RedisConstant;
import pers.sen.health.service.SetMealService;
import pers.sen.health.vo.CheckGroupVO;
import pers.sen.health.vo.SetmealVO;

import java.util.List;
import java.util.Set;

/**
 * @author Jason
 * @version 1.0.0
 * @date 2020/11/7 19:20
 * @Description TODO
 */
@Service
@Transactional
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {

    /**
     * 分页查询
     * @param queryPageBean 分页条件：当前页，每页条数，查询条件
     * @return 分页结果：总条数，当前页集合
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        // 1. 构造条件
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);

        // 2. page方法返回查询结果
        Page<Setmeal> page = null;
        if (StringUtils.isBlank(queryPageBean.getQueryString())) {
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);
        } else {
            queryWrapper.like("name", queryPageBean.getQueryString());
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);
        }

        // 3. 封装结果集
        PageResult pageResult = new PageResult(page.getTotal(), page.getRecords());
        return pageResult;
    }


    @Override
    public Boolean insertSetMeal(SetmealDTO setmealDTO) {
        String imgName = setmealDTO.getImg();
        // 判断图片是否被清理
        if (!RedisUtil.isMemberOfSet(RedisConstant.ALL_SETMEAL_PIC_SET,imgName)) {
            // 已经被清理抛出异常
            throw new RuntimeException("图片过期，请重新上传");
        }
        boolean b = saveOrUpdate(setmealDTO);
        Integer sid = setmealDTO.getId();
//        System.out.println("gid = " + gid);

        Integer[] checkgroupIds = setmealDTO.getCheckgroupIds();
        if (!EmptyUtil.isNullOrEmpty(checkgroupIds)) {
            for (Integer checkgroupId : checkgroupIds) {
                baseMapper.insertInfoByGid(sid, checkgroupId);
            }
        }
        RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET, setmealDTO.getImg());
        return b;
    }

    /**
     * 清理失效图片业务
     */
    @Override
    public void clearOssObject() {
        // 获取 set 集合 所有图片信息
        Set<String> members = RedisUtil.getMembersOfSet(RedisConstant.ALL_SETMEAL_PIC_SET);
        if(!EmptyUtil.isNullOrEmpty(members)){
            for (String uuidFileName : members) {
                // 遍历set中的图片，判断String中是否存在
                boolean existsKey = RedisUtil.existsKey(RedisConstant.SINGLE_PIC + uuidFileName);
                // 不存在，证明表单失效
                if(existsKey==false){
                    // 删除oss上的图片信息
                    AliyunUtils.deleteFile(uuidFileName);
                    System.out.println("-----阿里云oss删除垃圾图片："+ uuidFileName +"----");
                    // set集合删除图片信息
                    RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET,uuidFileName);
                    System.out.println("-----Redis-Set删除垃圾图片："+ uuidFileName +"----");
                }
            }
        }
    }

    // 查找套餐详情
    @Override
    public SetmealVO findSetMealDetailById(int id) {
        SetmealVO setmealVO = baseMapper.findSetMealById(id);

        List<CheckGroupVO> checkGroupVOList = baseMapper.findCheckGroupInfoBySid(id);
        for (CheckGroupVO checkGroupVO : checkGroupVOList) {
            List<CheckItem> checkItemList = baseMapper.findCheckItemByCid(checkGroupVO.getId());
            checkGroupVO.setCheckItemList(checkItemList);
        }

        setmealVO.setCheckGroups(checkGroupVOList);
        return setmealVO;
    }

    @Override
    public Setmeal findSetMealById(int id) {
        return baseMapper.findSetMealById(id);
    }


}
